package com.corecmd.tcloud.tcim.im;

import android.os.Handler;

import com.corecmd.tcloud.tcim.domain.ImLoginInfo;
import com.corecmd.tcloud.tcimcommon.im.common.PacketCodeC;
import com.corecmd.tcloud.tcimcommon.im.domain.LoginRequestPacket;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
public class ClientHandler extends SimpleChannelInboundHandler<String> {
    private Handler mHandler;
    private ImLoginInfo imLoginInfo;
    public ClientHandler(Handler handler,ImLoginInfo imLoginInfo){
        this.mHandler = handler;
        this.imLoginInfo = imLoginInfo;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端开始登录");
        Channel channel = ctx.channel();
        // 创建登录对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(this.imLoginInfo.getUserId());
        loginRequestPacket.setPlatform("android");
        // 编码
        ByteBuf buffer = new PacketCodeC().encode(loginRequestPacket);
        // 写数据
        channel.writeAndFlush(buffer);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String o) throws Exception {
        System.out.println("收到服务端消息："+o);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        if(channel.isActive()){
            ctx.close();
        }
    }
}
